﻿using System;
using System.Text;
using System.Web.Mvc;
using cludg.Web.Core.Controllers;
using cludg.Web.Core.Utils;
using cludg.Web.Core.ViewModels;

namespace cludg.Web.Core.RenderHelpers
{
	public static class TreeRenderHelper
	{
		public static MvcHtmlString RenderTree<T>(this HtmlHelper html, ITreeNode<T> treeRoot)
		{
			// Get view register from controller
			var controller = html.ViewContext.Controller as BaseController;
			if (controller == null)
			{
				throw new ApplicationException("RenderTree helper can be user only with BaseController objects.");
			}

			var itemType = treeRoot.GetType();
			var viewName = controller.ViewRegisterContainer.GetView(itemType);

			var result = new StringBuilder();
			result.Append(ViewRenderUtil.RenderViewToString(html.ViewContext, viewName, treeRoot));
			if (treeRoot.HasChildren)
			{
				foreach (var child in treeRoot.ChildNodes)
				{
					result.Append("<div style=\"padding-left: 30px;\">");
					result.Append(RenderTree(html, child));
					result.Append("</div>");
				}
			}
			return MvcHtmlString.Create(result.ToString());
		}
	}
}